//
//  GKZYHomeCourseAreaView.m
//  GKZY_CLASS
//
//  Created by KwokChun Cheung on 15/11/26.
//  Copyright © 2015年 eenet. All rights reserved.
//

#import "GKZYHomeCourseAreaView.h"
#import "GKZYHomeViewController.h"
#import "GKZYCourseListReq.H"

#import "HomeTabBarController.h"
#import "HomeNewViewController.h"

#import "xxptmobile.h"

#import "FCXRefreshFooterView.h"
#import "FCXRefreshHeaderView.h"
#import "UIScrollView+FCXRefresh.h"

@interface GKZYHomeCourseAreaView()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView *scroll;
@property (nonatomic, strong) UIView *scrollArea;
@property (nonatomic, strong) GKZYHomeInfoAreaView *infoView;
@property (nonatomic, strong) UITableView *table;
@end

@implementation GKZYHomeCourseAreaView{
    FCXRefreshHeaderView *headerView;
    FCXRefreshFooterView *footerView;
}

-(instancetype)init{
    if (self = [super init]) {
        
        self.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
        
        [self addSubview:self.scroll];
        [self.scroll mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.bottom.equalTo(self);
        }];
        
    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
    [self addRefreshView];
}

#pragma mark - UIScrollView+FCXRefresh


- (void)addRefreshView {
    
    __weak __typeof(self)weakSelf = self;
    
    //下拉刷新
    headerView = [self.table addHeaderWithRefreshHandler:^(FCXRefreshBaseView *refreshView) {
        [weakSelf refreshAction];
    }];
    
    //上拉加载更多
    footerView = [self.table addFooterWithRefreshHandler:^(FCXRefreshBaseView *refreshView) {
        [weakSelf loadMoreAction];
    }];
    
}

- (void)refreshAction {
    __weak UITableView *weakTableView = self.table;
    __weak FCXRefreshHeaderView *weakHeaderView = headerView;
    __weak __typeof(self)weakSelf = self;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.superController requestCatBy:weakSelf.superController.sid];
        [weakTableView reloadData];
        [weakHeaderView endRefresh];
    });
}

- (void)loadMoreAction {
    __weak UITableView *weakTableView = self.table;
    __weak FCXRefreshFooterView *weakFooterView = footerView;
    __weak __typeof(self)weakSelf = self;
    
    if (self.courses.count < ([OO_PAGE_NO intValue] * [self.superController.currentPage intValue])){
        [weakFooterView endRefresh];
        return;
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        weakSelf.superController.currentPage = @([weakSelf.superController.currentPage intValue]+1);
        
        GKZYCourseListReq *courseReq = [GKZYCourseListReq new];
        courseReq.sid = weakSelf.superController.sid;
        courseReq.cid = weakSelf.superController.currentCid;
        courseReq.pageNo = [weakSelf.superController.currentPage stringValue];
        courseReq.pageSize = OO_PAGE_NO;
        
        [weakSelf.superController requestList:courseReq isAdd:YES onLoading:NO];
        
        [weakTableView reloadData];
        [weakFooterView endRefresh];
    });
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.courses.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 12;
    }
    return 6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellName = @"cell";
    GKZYHomeCourseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!cell){
        cell = [[GKZYHomeCourseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    GKZYHomeCourseModel *model = self.courses[indexPath.section];
    cell.model = model;
    cell.delegate = self.superController;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GKZYHomeCourseModel *model = self.courses[indexPath.section];
    HomeNewModel *homeNewModel = [HomeNewModel new];
//    if (indexPath.section==0) {
//        NSString *termCourseId = @"336f13c8ac109244335a335a2d5195c8";
//        NSString *courseId = @"6f397708147247be83000e8ea40a967c";
//        NSString *classId = @"eff40231ac1092471f2a1f2a44f40200";
//        NSString *userId = @"testClassStu1";
//        
//        homeNewModel.courseId = courseId;
//        homeNewModel.classId = classId;
//        homeNewModel.termCourseId = termCourseId;
//        homeNewModel.userId = userId;
//
//    }else{
        homeNewModel.courseId = model.courseId;
        homeNewModel.classId = model.classId;
        homeNewModel.termCourseId = model.identity;
        homeNewModel.userId = self.superController.sid;
//    }
    
    HomeTabBarController *vc = [[HomeTabBarController alloc]initOnShell];
    vc.model = homeNewModel;
    vc.transitioningDelegate = self.superController;
    
    //由于present需要等待vc的ViewDidLoad前的生命周期完成且主线程优先级较低的方法.故需要调用主线程直接执行
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.superController presentViewController:vc animated:YES completion:nil];
    });
}
#pragma mark - Setter For Property

-(void)setInfoArray:(NSMutableArray<GKZYHomeInfoModel *> *)infoArray{
    _infoArray = infoArray;
    if (infoArray) {
        self.infoView.infoArray = infoArray;
    }
}

-(void)setCourses:(NSMutableArray<GKZYHomeCourseModel *> *)courses{
    _courses = courses ? courses : [[NSMutableArray alloc] init];
    [self.table reloadData];
}

#pragma mark - Getter For UI

-(UIScrollView *)scroll{
    if (!_scroll) {
        _scroll = ({
            UIScrollView *scroll = [UIScrollView new];
            
            self.scrollArea = [UIView new];
            [scroll addSubview:self.scrollArea];
            [self.scrollArea mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.left.right.bottom.equalTo(scroll);
                make.width.height.equalTo(scroll);
            }];
            
            [self.scrollArea addSubview:self.infoView];
            [self addGapLineWith:self.infoView on:LinePositionBottom];
            [self.infoView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.left.right.equalTo(self.scrollArea);
                make.height.equalTo(@(80));
            }];
            
            [self.scrollArea addSubview:self.table];
            [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.equalTo(self.scrollArea);
                make.top.equalTo(self.infoView.mas_bottom);
            }];
            
            scroll;
        });
    }
    return _scroll;
}

-(GKZYHomeInfoAreaView *)infoView{
    if (!_infoView) {
        _infoView = ({
            GKZYHomeInfoAreaView *view = [GKZYHomeInfoAreaView new];
            view;
        });
    }
    return _infoView;
}

-(UITableView *)table{
    if (!_table) {
        _table = ({
            UITableView *table = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
            table.backgroundColor = [UIColor clearColor];
            table.delegate = self;
            table.dataSource = self;
            table.estimatedRowHeight = 100;
            table.rowHeight = UITableViewAutomaticDimension;
//            table.bounces = NO;
            table;
        });
    }
    return _table;
}

#pragma mark - Tools Methods

typedef NS_ENUM(NSUInteger, LinePosition) {
    LinePositionTop,
    LinePositionLeft,
    LinePositionRight,
    LinePositionBottom,
};
-(void)addGapLineWith:(UIView *)view on:(LinePosition)posit{
    //用于防止重复插入
    NSInteger tagNumber = 960;
    switch (posit) {
        case LinePositionTop:
            tagNumber = 961;
            break;
        case LinePositionLeft:
            tagNumber = 962;
            break;
        case LinePositionRight:
            tagNumber = 963;
            break;
        case LinePositionBottom:
            tagNumber = 964;
            break;
        default:
            break;
    }
    UIView *exist = [view viewWithTag:tagNumber];
    if (exist) { return; }
    
    CGFloat lineSizeUnit = 0.5;
    UILabel *line = [UILabel new];
    line.backgroundColor = [UIColor lightGrayColor];
    line.tag = tagNumber;
    
    [view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        if (posit==LinePositionRight || posit==LinePositionLeft) {
            if (posit==LinePositionRight) {
                make.right.equalTo(view);
            }else if (posit==LinePositionLeft){
                make.left.equalTo(view);
            }
            make.top.equalTo(view);
            make.height.equalTo(view);
            make.width.equalTo(@(lineSizeUnit));
        }else if (posit==LinePositionTop || posit==LinePositionBottom){
            if (posit==LinePositionTop) {
                make.top.equalTo(view);
            }else if (posit==LinePositionBottom){
                make.bottom.equalTo(view);
            }
            make.height.equalTo(@(lineSizeUnit));
            make.width.equalTo(view);
        }
    }];
}

@end
